//
//  HFStatusListViewModel.swift
//  sinaMicroBlog
//
//  Created by mac on 15/11/19.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class HFStatusListViewModel: NSObject {
    class func loadData(since_id: Int, max_id: Int, finished: (array: [HFStatus]?) ->()) {
        let urlString = "2/statuses/home_timeline.json"
        guard let token = HFUserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("您尚未登录")
            return
        }
        var parameters = ["access_token": token]
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        HFNetWorkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {

                finished(array: nil)
                return
            }
            if let array = result!["statuses"] as? [[String : AnyObject]] {
                var list = [HFStatus]()
                for item in array {
                    let status = HFStatus(dict: item)
                    list.append(status)
                }
                finished(array: list)
                HFStatusListViewModel.cacheStatusImage(list, finished: finished)
            }
        }
    }
    
    //单张图片下载存储
    private class func cacheStatusImage(array: [HFStatus], finished:(array: [HFStatus]?) -> ()) {
        if array.count == 0 {
            finished(array: nil)
            return
        }
        
        let group = dispatch_group_create()
        
        for status in array {
            if let imageurls = status.pictureURLs {
                if imageurls.count != 1 {
                    continue
                }
                
                for url in imageurls {
                    
                    //GCD
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("wancheng")
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(array: array)
        }
        
    }

}
